package com.mohunhun.controller;

import com.mohunhun.common.AppResult;
import com.mohunhun.common.ResultCode;
import com.mohunhun.config.AppConfig;
import com.mohunhun.exception.ApplicationException;
import com.mohunhun.model.User;
import com.mohunhun.services.IUserService;
import com.mohunhun.utils.AliyunOSSOperator;
import com.mohunhun.utils.MD5Util;
import com.mohunhun.utils.StringUtil;
import com.mohunhun.utils.UUIDUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.Jar;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

import static com.mohunhun.utils.FileHashUtils.computeSHA256;

// 返回输的的Controller
@RestController
// 路由映射
@RequestMapping("/user")
@Slf4j
@Tag(name = "用户接口")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private AliyunOSSOperator aliyunOSSOperator;


    /**
     * 用户注册功能
     *
     * @param username       用户名
     * @param nickname       昵称
     * @param password       密码
     * @param passwordRepeat 重复密码
     * @return 注册结果，成功返回AppResult.success()
     */
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public AppResult register(@Parameter(description = "用户名") @RequestParam("username") @NonNull String username,
                              @Parameter(description = "用户昵称") @RequestParam("nickname") @NonNull String nickname,
                              @Parameter(description = "密码") @RequestParam("password") @NonNull String password,
                              @Parameter(description = "确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        /*if (StringUtil.isEmpty(username)
                || StringUtil.isEmpty(nickname)
                || StringUtil.isEmpty(password)
                || StringUtil.isEmpty(passwordRepeat)) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }*/

        // 校验密码与重复密码是否相同
        if (!password.equals(passwordRepeat)) return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);

        // 准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        String salt = UUIDUtil.UUID_32();
        String ciphertext = MD5Util.md5(password, salt);
        user.setPassword(ciphertext);
        user.setSalt(salt);
        userService.creatNormalUser(user);

        return AppResult.success();
    }


    /**
     * 用户登录接口
     *
     * @param username 用户名
     * @param password 密码
     * @return 登录结果
     */
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @Parameter(description = "用户名") @RequestParam("username") @NonNull String username,
                           @Parameter(description = "密码") @RequestParam("password") @NonNull String password) {
        User user = userService.login(username, password);
        if (user == null) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }

        // true表示，没有session时，创建一个新的session
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION, user);

        return AppResult.success();
    }


    /**
     * 获取用户信息
     *
     * @param request HTTP请求对象，用于获取请求相关信息
     * @param id      用户ID，可选参数，如果未提供则可能返回当前登录用户的信息
     * @return AppResult 包含用户信息的统一返回结果
     */
    @Operation(summary = "获取用户信息")
    @GetMapping("/info")
    public AppResult getUserInfo(HttpServletRequest request,
                                 @Parameter(description = "用户id") @RequestParam(value = "id", required = false) Long id) {

        User user = null;
        if (id == null) {
            user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);
        } else {
            user = userService.selectById(id);
        }

        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        return AppResult.success(user);
    }


    /**
     * 用户退出登录接口
     *
     * @param request HTTP请求对象，包含用户会话信息
     * @return AppResult 统一返回结果对象，包含退出成功的信息
     */
    @Operation(summary = "退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession();

        if (session != null) {
            log.info("退出成功");
            session.invalidate();
        }


        return AppResult.success("退出成功");
    }


    @Operation(summary = "修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @Parameter(description = "用户名") @RequestParam(value = "username", required = false) String username,
                                @Parameter(description = "用户昵称") @RequestParam(value = "nickname", required = false) String nickname,
                                @Parameter(description = "性别") @RequestParam(value = "gender", required = false) Byte gender,
                                @Parameter(description = "邮件") @RequestParam(value = "email", required = false) String email,
                                @Parameter(description = "手机号") @RequestParam(value = "phoneNum", required = false) String phoneNum,
                                @Parameter(description = "个人简介") @RequestParam(value = "remark", required = false) String remark) {


        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark) && gender == null) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);

        userService.modifyInfo(updateUser);


        session.setAttribute(AppConfig.USER_SESSION, userService.selectById(user.getId()));

        return AppResult.success();
    }


    @Operation(summary = "更新头像")
    @PostMapping("/uploadAvatar")
    public AppResult uploadAvatar(HttpServletRequest request,
                                  @Parameter(description = "用户ID") @RequestParam("id") @NonNull Long userId,
                                  @Parameter(description = "二进制文件") @RequestParam("avatar") @NonNull MultipartFile avatar) throws Exception {

        log.info("用户 {} 上传头像文件：{}", userId, avatar.getOriginalFilename());

        if (avatar.isEmpty()) {
            return AppResult.failed("文件为空");
        }

        String originalFilename = avatar.getOriginalFilename();
        if (originalFilename == null || originalFilename.lastIndexOf(".") == -1) {
            return AppResult.failed("文件名无效");
        }

        // 1. 计算上传文件的哈希值（SHA-256）
        byte[] fileBytes = avatar.getBytes();
        String newFileHash = computeSHA256(fileBytes);

        // 2. 查询当前用户
        User user = userService.selectById(userId);
        if (user == null) {
            log.warn("用户不存在，ID: {}", userId);
            return AppResult.failed("用户不存在");
        }

        // 3. 比对哈希值：如果相同，直接返回当前头像 URL
        if (newFileHash.equals(user.getAvatarHash())) {
            log.info("用户 {} 上传的头像与当前头像内容相同，跳过上传", userId);
            return AppResult.success(user.getAvatarUrl());
        }

        // 4. 不同则上传新文件
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uniqueFileName = UUID.randomUUID().toString().replace("-", "") + extName;
        String newAvatarUrl = aliyunOSSOperator.upload(fileBytes, uniqueFileName);

        // 5. 更新数据库：avatarUrl + avatarHash
        userService.updateAvatarUrlAndHash(userId, newAvatarUrl, newFileHash);

        // 6. 更新 session 中的用户信息（如果存在）
        HttpSession session = request.getSession(false);
        if (session != null) {
            User sessionUser = (User) session.getAttribute(AppConfig.USER_SESSION);
            if (sessionUser != null && sessionUser.getId().equals(userId)) {
                sessionUser.setAvatarUrl(newAvatarUrl);
                sessionUser.setAvatarHash(newFileHash);
                session.setAttribute(AppConfig.USER_SESSION, sessionUser);
            }
        }

        log.info("用户 {} 头像更新成功，新URL: {}", userId, newAvatarUrl);
        return AppResult.success((Object) newAvatarUrl);
    }


    @Operation(summary = "更新密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @Parameter(description = "原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @Parameter(description = "新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @Parameter(description = "确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        if (!newPassword.equals(passwordRepeat)) {
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }


        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        userService.modifyPassword(user.getId(), newPassword, oldPassword);


        session.invalidate();


        return AppResult.success();
    }
}
